package com.peanut.service.impl;

import com.peanut.entity.BookTypeFirst;
import com.peanut.entity.BookTypeSecond;
import com.peanut.entity.Page;
import com.peanut.entity.vo.BookVO;
import com.peanut.mapper.BookMapper;
import com.peanut.service.BookService;
import com.spring.annotation.Autowired;
import com.spring.annotation.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {
	@Autowired
	private BookMapper mapper;
	
	@Override
	public Page<BookVO> pageQueryAll(Integer currentPage, Integer pageSize) {
		return pageQueryAllByCondition(new BookVO(),currentPage,pageSize);
	}
	
	@Override
	public Page<BookVO> pageQueryAllByCondition(BookVO vo, Integer currentPage, Integer pageSize) {
		int total = mapper.queryCount(vo);
		int pageCount = (int) (Math.ceil((double) total / pageSize));     // 计算分页数量和当前处于第几页
		currentPage = currentPage > pageCount ? pageCount : currentPage;
		
		Page<BookVO> listPage = new Page<>();
		listPage.setTotal(total);
		listPage.setPageCount(pageCount);
		listPage.setPageSize(pageSize);
		listPage.setCurrentPage(currentPage);
		
		
		if(total != 0){
			List<BookVO> bookVOS = mapper.queryAllByCondition(vo,(currentPage - 1) * pageSize, pageSize);
			listPage.setData(bookVOS);
		}
		return listPage;
	}
	
	@Override
	public int updateById(BookVO vo) {
		return mapper.updateById(vo);
	}
	
	@Override
	public List<BookTypeFirst> queryAllBookType() {
		List<BookTypeFirst> bookTypeFirsts = mapper.queryAllType();
		if(bookTypeFirsts!= null && !bookTypeFirsts.isEmpty()){
			for (BookTypeFirst bookTypeFirst : bookTypeFirsts) {
				List<BookTypeSecond> bookTypeSeconds = mapper.querySecondType(bookTypeFirst.getId());
				bookTypeFirst.setSecondList(bookTypeSeconds);
			}
		}
		return bookTypeFirsts;
	}
}
